﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_BLL;
using System.Reflection;
using ANZ_AIM_BLL.Model;
using ANZ_AIM_FRAMEWORK;
using ANZ_AIM_GUI.Utils;
using log4net;

namespace ANZ_AIM_GUI
{
    public partial class frmAdmin : Form
    {
        //log4net
        private static readonly ILog logger = LogManager.GetLogger(typeof(frmAdmin));

        private DataTable dataTableUser;
        private DataTable dataTableRole;

        AppParam param = AppParam.Instance;

        public frmAdmin()
        {
            InitializeComponent();
        }

        private void frmAdmin_Load(object sender, EventArgs e)
        {
            try
            {
                LoadUserManagementData();
                cboStatus.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void LoadUserManagementData()
        {
            try
            {
                // Load data
                dgvUserList.DataSource = null;
                dgvUserList.Columns.Clear();
                UserBLL userBLL = new UserBLL();
                dataTableUser = userBLL.GetUsers();
                dgvUserList.DataSource = dataTableUser;
                dgvUserList.AutoResizeColumns();

                // Set col header
                dgvUserList.Columns[0].Visible = false;
                dgvUserList.Columns[1].HeaderText = "User Name";
                dgvUserList.Columns[2].HeaderText = "Full Name";
                dgvUserList.Columns[3].HeaderText = "Email";
                dgvUserList.Columns[4].HeaderText = "Role";
                dgvUserList.Columns[5].HeaderText = "Active";
                dgvUserList.Columns[6].HeaderText = "Created Date";
                dgvUserList.Columns[6].DefaultCellStyle.Format = "dd MMM, yyyy";
                dgvUserList.Columns[7].HeaderText = "Created By";
                dgvUserList.Columns[8].Visible = false;
                dgvUserList.Columns[9].Visible = false;


                DataGridViewImageColumn colEdit = new DataGridViewImageColumn();
                colEdit.HeaderText = "Edit";
                colEdit.Image = imgIcon.Images[1];
                colEdit.Width = 50;
                colEdit.Name = "colEdit";
                dgvUserList.Columns.Add(colEdit);

                DataGridViewImageColumn colDelete = new DataGridViewImageColumn();
                colDelete.HeaderText = "Delete";
                colDelete.Image = imgIcon.Images[0];
                colDelete.Width = 70;
                colDelete.Name = "colDelete";
                dgvUserList.Columns.Add(colDelete);

                DataGridViewImageColumn colResetPassword = new DataGridViewImageColumn();
                colResetPassword.HeaderText = "Reset Password";
                colResetPassword.Image = imgIcon.Images[2];
                colResetPassword.Width = 90;
                colResetPassword.Name = "colResetPassword";
                dgvUserList.Columns.Add(colResetPassword);

                // load data for cbo Role
                RoleBLL roleBll = new RoleBLL();
                dataTableRole = roleBll.GetRoles();

                //Add a new row to table
                DataRow newRow = dataTableRole.NewRow();
                newRow["RoleID"] = 0;
                newRow["RoleName"] = "All";

                //bind data to cboRole
                dataTableRole.Rows.InsertAt(newRow, 0);
                cboRole.DataSource = dataTableRole;
                cboRole.DisplayMember = "RoleName";
                cboRole.ValueMember = "RoleID";

                //Resize all columns
                //dgvUserList.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvUserList.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                //dgvUserList.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvUserList.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvUserList.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvUserList.Columns[6].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvUserList.Columns[7].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvUserList.Columns[8].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            }
            catch (Exception ex) { throw ex; }
        }

        private void dgvUserList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush b = new SolidBrush(dgvUserList.RowHeadersDefaultCellStyle.ForeColor))
            {
                e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
            }
        }

        private void grdUserList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1) return;

            var msg = String.Empty;
            try
            {
                if (e.RowIndex != -1)
                {
                    UserBLL userBLL = new UserBLL();
                    string userID = dgvUserList.SelectedCells[0].Value.ToString();
                    string role = dgvUserList.SelectedCells[4].Value.ToString();
                    User user = userBLL.GetById(userID);

                    switch (e.ColumnIndex)
                    {
                        case 10: // edit user                       
                            frmAdminUser frmUser = new frmAdminUser(MiscHelper.FORM_OPMODE_EDIT, user);
                            frmUser.ShowDialog(this);
                            //LoadUserManagementData(); //08Jan2015 Fix reset filter condition and user grid issue
                            Search(); //08Jan2015 Fix reset filter condition and user grid issue
                            break;
                        case 11:// delete
                            if (role.Contains("Admin"))
                            {
                                MessageBox.Show("Can not delete admin!");
                                return;
                            }
                            DialogResult result = MessageBox.Show("Are you sure to delete this account?", "Delete confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button2);
                            if (result == DialogResult.Yes)
                            {
                                msg = Constant.SYS_MSG_DEL_USER;
                                userBLL.DeleteUser(userID);
                                //LoadUserManagementData(); //08Jan2015 Fix reset filter condition and user grid issue
                                Search(); //08Jan2015 Fix reset filter condition and user grid issue
                                MessageBox.Show("User has been deleted");
                            }
                            break;
                        case 12:// reset password
                            DialogResult resultReset = MessageBox.Show(this, "Are you sure to reset password for this User?", "Reset Password", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                            if (resultReset == DialogResult.Yes)
                            {
                                AESHelper aes = new AESHelper();
                                string newPass = MiscHelper.GetRandomString();

                                user.Password = aes.EncryptToString(newPass);
                                user.LastUpdatedBy = param.UserName;
                                user.LastUpdatedDate = MiscHelper.DateTimeToShort(DateTime.Now);
                                user.LastChangedPwd = MiscHelper.DateTimeToShort(DateTime.Now);
                                user.IsLock = false;
                                user.MustChangePwd = "Y";

                                userBLL.Save(user);
                                frmPassword fmPwd = new frmPassword(newPass, "Password reset to new password:");
                                fmPwd.ShowDialog();
                            }
                            break;
                        default:
                            return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
                return;
            }

            try
            {
                if (!String.IsNullOrEmpty(msg))
                {
                    LogBLL logBll = new LogBLL();
                    logBll.Description = msg;
                    logBll.Log(this.FindForm(), param.UserName);
                }
            }
            catch { }
        }

        private void cmdAddNewUser_Click(object sender, EventArgs e)
        {
            try
            {
                User user = new User();
                frmAdminUser fmAdminUser = new frmAdminUser(MiscHelper.FORM_OPMODE_ADD_NEW, user);
                fmAdminUser.ShowDialog(this);
                //LoadUserManagementData(); //08Jan2015 Fix reset filter condition and user grid issue
                Search(); //08Jan2015 Fix reset filter condition and user grid issue
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void btnSearchUser_Click(object sender, EventArgs e)
        {
            try
            {
                Search();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void Search()
        {
            try
            {
                string userName = txtUsername.Text.Trim();
                string role = cboRole.GetItemText(cboRole.SelectedItem);
                string isActive = cboStatus.GetItemText(cboStatus.SelectedItem);
                if (string.IsNullOrEmpty(userName))
                {
                    userName = null;
                }
                if (role.Equals("All"))
                {
                    role = null;
                }
                if (isActive.Equals("All"))
                {
                    isActive = null;
                }
                else
                {
                    isActive = cboStatus.GetItemText(cboStatus.SelectedItem).ToString().Equals("Active") ? "1" : "0";
                }

                UserBLL userBll = new UserBLL();
                dataTableUser = userBll.Search(userName, role, isActive);
                dgvUserList.DataSource = null;
                dgvUserList.Columns.Clear();
                dgvUserList.DataSource = dataTableUser;
                dgvUserList.AutoResizeColumns();

                // Set col header
                dgvUserList.Columns[0].Visible = false;
                dgvUserList.Columns[1].HeaderText = "UserName";
                dgvUserList.Columns[2].HeaderText = "FullName";
                dgvUserList.Columns[3].HeaderText = "Email";
                dgvUserList.Columns[4].HeaderText = "Role";
                dgvUserList.Columns[5].HeaderText = "Active";
                dgvUserList.Columns[6].HeaderText = "Created Date";
                dgvUserList.Columns[6].DefaultCellStyle.Format = "dd MMM, yyyy";
                dgvUserList.Columns[7].HeaderText = "Created By";
                dgvUserList.Columns[8].Visible = false;
                dgvUserList.Columns[9].Visible = false;

                DataGridViewImageColumn colEdit = new DataGridViewImageColumn();
                colEdit.HeaderText = "Edit";
                colEdit.Image = imgIcon.Images[1];
                colEdit.Width = 50;
                colEdit.Name = "colEdit";
                dgvUserList.Columns.Add(colEdit);

                DataGridViewImageColumn colDelete = new DataGridViewImageColumn();
                colDelete.HeaderText = "Delete";
                colDelete.Image = imgIcon.Images[0];
                colDelete.Width = 70;
                colDelete.Name = "colDelete";
                dgvUserList.Columns.Add(colDelete);

                DataGridViewImageColumn colResetPassword = new DataGridViewImageColumn();
                colResetPassword.HeaderText = "Reset Password";
                colResetPassword.Image = imgIcon.Images[2];
                colResetPassword.Width = 120;
                colResetPassword.Name = "colResetPassword";
                dgvUserList.Columns.Add(colResetPassword);
            }
            catch (Exception ex) { throw; }
        }
    }
}
